<template>
  <Dialog
    :draggable="false"
    :title="dialogTitle"
    v-model="dialogVisible"
    style="min-width: 1200px"
    scroll
    :max-height="600"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="124px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <!-- 采购类型： SERVICE/EQUIPMENT/NGINEERING/MATERIAL/DIRECT/MINOR -->
      <el-form-item label="采购类型" prop="purchaseType">
        <el-select v-model="formData.purchaseType" placeholder="请选择采购类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PURCHASE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 非小额类 -->
      <template v-if="type == 'NoSmall'">
        <el-form-item label="采购事项名称" prop="planName">
          <el-input v-model="formData.planName" placeholder="请输入采购事项名称" />
        </el-form-item>
        <el-form-item label="预算归属部门" prop="budgetDepartmentId">
          <el-select
            v-model="formData.budgetDepartmentId"
            filterable
            placeholder="请选择预算归属部门"
            :filter-method="handleDeptFilter"
          >
            <el-option
              v-for="item in DeptPageList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="需求使用部门" prop="applicationDepartmentId">
          <el-select
            v-model="formData.applicationDepartmentId"
            filterable
            placeholder="请选择需求使用部门"
            :filter-method="handleDeptFilter"
          >
            <el-option
              v-for="item in DeptPageList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采购计划编号" prop="planNo">
          <el-input v-model="formData.planNo" disabled placeholder="系统自动填写" />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="formData.projectName" placeholder="请输入项目名称" disabled />
        </el-form-item>
        <el-form-item label="采购方式" prop="purchaseMethod">
          <el-select v-model="formData.purchaseMethod" placeholder="请选择采购方式">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.PURCHASE_METHOD)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="质保期/维保期" prop="warrantyPeriod">
          <el-input v-model="formData.warrantyPeriod" placeholder="如有，则填写" />
        </el-form-item>
        <el-form-item label="原合同期限" prop="originalContractTime">
          <el-date-picker
            v-model="formData.originalContractTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="原合同金额" prop="originalContractAmount">
          <el-input v-model="formData.originalContractAmount" placeholder="如有，则填写">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="合同使用履约情况" prop="contractPerformance">
          <el-input
            v-model="formData.contractPerformance"
            :rows="3"
            type="textarea"
            maxlength="400"
            show-word-limit
            placeholder="备注内容......"
          />
        </el-form-item>
        <el-form-item label="本次采购预估单价来源说明" prop="estimatedPriceSource">
          <el-input
            v-model="formData.estimatedPriceSource"
            :rows="3"
            maxlength="400"
            show-word-limit
            type="textarea"
            placeholder="备注内容......"
          />
        </el-form-item>
        <!-- 导入导出弹窗 -->
        <div style="text-align: center; margin-bottom: 20px" v-if="formData.purchaseType">
          <el-button type="primary" plain style="margin-right: 20px" @click="handleImport"
            >Excel导入附件进行采购订单</el-button
          >
        </div>
        <!-- 工程类 -->
        <template v-if="formData.purchaseType == 'ENGINEERING'">
          <el-form-item
            prop="engineeringDetailSaveReqVOS"
            :rules="formRules.engineeringDetailSaveReqVOS"
            style="display: none"
          />
          <ContentWrap>
            <el-table
              :data="formData.engineeringDetailSaveReqVOS"
              style="width: 100%; margin-bottom: 20px"
            >
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="purchaseContent" label="采购内容（详细）" min-width="260" />
              <el-table-column prop="estimatedQuantity" label="预估采购数量" min-width="120" />
              <el-table-column
                prop="totalPriceLimit"
                label="总价限价（单位：万元，人民币）"
                min-width="260"
              />
              <el-table-column prop="remark" label="备注" />
            </el-table>
          </ContentWrap>
          <div style="display: flex">
            <el-form-item label="需到货时间" prop="requiredDeliveryTime" style="flex: 1">
              <el-date-picker
                v-model="formData.requiredDeliveryTime"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="选择需到货时间"
              />
            </el-form-item>
            <el-form-item
              label="是否含有非标配件"
              label-width="130"
              prop="hasNonStandardParts"
              style="flex: 1; margin-left: 20px"
            >
              <el-checkbox
                v-model="formData.hasNonStandardParts"
                true-value="1"
                false-value="0"
                label="请确认"
              />
            </el-form-item>
          </div>
          <div style="display: flex">
            <el-form-item label="施工时间" prop="constructionTime" style="flex: 1">
              <el-date-picker
                v-model="formData.constructionTime"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="选择施工时间"
              />
            </el-form-item>
            <el-form-item
              label="是否含暂列金"
              label-width="130"
              prop="hasProvisionalSum"
              style="flex: 1; margin-left: 20px"
            >
              <el-checkbox
                v-model="formData.hasProvisionalSum"
                true-value="1"
                false-value="0"
                label="请确认"
              />
            </el-form-item>
          </div>
          <el-form-item label="施工日期" prop="construction">
            <el-date-picker
              v-model="formData.construction"
              value-format="YYYY-MM-DD"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-220px"
            />
            <el-button disabled>{{ dayLength }}天</el-button>
          </el-form-item>
          <el-form-item label="施工期间负责人" prop="constructionLeader">
            <el-input v-model="formData.constructionLeader" placeholder="请输入施工期间负责人" />
          </el-form-item>
        </template>

        <!-- 服务类 -->
        <template v-if="formData.purchaseType == 'SERVICE'">
          <el-form-item
            prop="serviceDetailSaveReqVOS"
            :rules="formRules.serviceDetailSaveReqVOS"
            style="display: none"
          />
          <ContentWrap>
            <el-table
              :data="formData.serviceDetailSaveReqVOS"
              style="width: 100%; margin-bottom: 20px"
            >
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="purchaseContent" label="采购内容（详细）" min-width="260" />
              <el-table-column prop="servicePeriod" label="服务期限" min-width="120" />
              <el-table-column prop="serviceLocation" label="服务地点" min-width="120" />
              <el-table-column
                prop="supplierQualification"
                label="供应商资质要求"
                min-width="260"
              />
              <el-table-column prop="technicalReview" label="技术评审单" min-width="260" />
              <el-table-column prop="currentInventory" label="现有库存数量" min-width="260" />
              <el-table-column prop="unit" label="单位" min-width="60" />
              <el-table-column
                prop="estimatedQuantity"
                label="预估采购数量"
                min-width="260"
                align="center"
              />
              <el-table-column
                prop="estimatedUnitPrice"
                label="预估单价（元/含税）"
                align="center"
                min-width="260"
              />
              <el-table-column prop="totalAmount" label="合计" align="center" min-width="260" />
            </el-table>
          </ContentWrap>
        </template>
        <!-- 物资类 -->
        <template v-if="formData.purchaseType == 'MATERIAL'">
          <el-form-item
            prop="materialDetailSaveReqVOS"
            :rules="formRules.materialDetailSaveReqVOS"
            style="display: none"
          />
          <ContentWrap>
            <el-table
              :data="formData.materialDetailSaveReqVOS"
              style="width: 100%; margin-bottom: 20px"
            >
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="materialCode" label="物料编码（NC编码）" width="160" />
              <el-table-column
                prop="materialName"
                label="物料名称（与NC编码中对应上）"
                width="240"
              />
              <el-table-column prop="unit" label="单位" width="60" />
              <el-table-column prop="specification" label="规格(产品的最小包装规格)" width="200" />
              <el-table-column prop="acceptanceStandard" label="物料/收货标准" width="180" />
              <el-table-column prop="brandRequirements" label="产品要求或参考品牌" width="180" />
              <el-table-column
                prop="packagingRequirements"
                label="送货/产品外包装要求"
                width="180"
              />
              <el-table-column
                prop="estimatedQuantity"
                label="预估采购数量（年用量）"
                align="center"
                width="180"
              />
              <el-table-column
                prop="estimatedUnitPrice"
                label="预估单价/限价（元/含税）"
                align="center"
                width="220"
              />
              <el-table-column prop="totalAmount" label="合计" width="220" />
            </el-table>
          </ContentWrap>
        </template>
        <!-- 设备类 -->
        <template v-if="formData.purchaseType == 'EQUIPMENT'">
          <el-form-item
            prop="equipmentDetailSaveReqVOS"
            :rules="formRules.equipmentDetailSaveReqVOS"
            style="display: none"
          />
          <ContentWrap>
            <el-table
              :data="formData.equipmentDetailSaveReqVOS"
              style="width: 100%; margin-bottom: 20px"
            >
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="category" label="分类" width="120" />
              <el-table-column prop="equipmentName" label="设备名称" width="120" />
              <el-table-column prop="unit" label="单位" width="60" />
              <el-table-column prop="parameterRequirements" label="参数要求" width="180" />
              <el-table-column prop="supplierQualification" label="供应商资质要求" width="180" />
              <el-table-column prop="reviewRequirements" label="商务或技术评审点要求" width="180" />
              <el-table-column
                prop="estimatedQuantity"
                label="预估采购数量"
                align="center"
                width="120"
              />
              <el-table-column
                prop="estimatedUnitPrice"
                label="预估单价（元/含税）"
                align="center"
                width="160"
              />
              <el-table-column prop="totalAmount" label="合计" align="center" width="180" />
            </el-table>
          </ContentWrap>
        </template>
      </template>

      <!-- 小额 -->
      <template v-if="type == 'Small'">
        <el-form-item label="采购事项名称" prop="planName">
          <el-input v-model="formData.planName" placeholder="请输入采购事项名称" />
        </el-form-item>
        <template v-if="formData.purchaseType == 'DIRECT'">
          <el-form-item label="实施小组组成" prop="implementationTeam">
            <el-input v-model="formData.implementationTeam" placeholder="请输入实施小组组成" />
          </el-form-item>
          <el-form-item label="谈判报价方式" prop="negotiationMethod">
            <el-input v-model="formData.negotiationMethod" placeholder="请输入谈判报价方式" />
          </el-form-item>
          <el-form-item label="供应商选择原则" prop="supplierSelectionPrinciple">
            <el-input
              v-model="formData.supplierSelectionPrinciple"
              placeholder="请输入供应商选择原则"
            />
          </el-form-item>
        </template>
        <el-form-item label="项目理由" prop="projectReason">
          <el-input
            v-model="formData.projectReason"
            :rows="3"
            maxlength="400"
            show-word-limit
            type="textarea"
            placeholder="请输入项目理由"
          />
        </el-form-item>
        <!-- 导入导出弹窗 -->
        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" plain style="margin-right: 20px" @click="handleImport"
            >Excel导入附件进行采购订单</el-button
          >
        </div>
        <ContentWrap>
          <el-form-item
            prop="minorDetailSaveReqVOS"
            :rules="formRules.minorDetailSaveReqVOS"
            style="display: none"
          />
          <el-table :data="formData.minorDetailSaveReqVOS" style="width: 100%; margin-bottom: 20px">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="itemName" label="物料/服务/工程名称" width="180" />
            <el-table-column prop="unit" label="单位" width="60" />
            <el-table-column prop="specModel" label="规格型号" width="100" />
            <el-table-column prop="acceptanceStandard" label="货物/验收标准" width="180" />
            <el-table-column prop="originPlace" label="产地" width="80" />
            <el-table-column
              prop="estimatedQuantity"
              label="预估采购数量"
              align="center"
              width="180"
            />
            <el-table-column
              prop="estimatedUnitPrice"
              label="预估单价（含税/万元）"
              align="center"
              width="180"
            />
            <el-table-column
              prop="totalAmount"
              label="合计（含税/万元）"
              align="center"
              width="180"
            />
          </el-table>
        </ContentWrap>
      </template>

      <el-form-item label="备注说明" prop="remark">
        <el-input
          v-model="formData.remark"
          :rows="3"
          maxlength="400"
          show-word-limit
          type="textarea"
          placeholder="备注内容......"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        @click="auditForm"
        type="primary"
        :disabled="auditLoaing || disabled"
        v-if="formData.status == 0 && formType != 'create'"
        >提交审核</el-button
      >
      <el-button @click="submitForm" type="primary" :disabled="formLoading || disabled"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <PurchasePlanImportForm ref="importFormRef" @success="importHandler" />
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import PurchasePlanImportForm from './PurchasePlanImportForm.vue'
import { PurchasePlanApi, PurchasePlanSaveReqVO } from '@/api/erp/purchase/plan'
import { getDeptPage, DeptVO, getSimpleDeptList } from '@/api/system/dept'
import { formatDate } from '@/utils/formatTime.js'
import { ElMessageBox } from 'element-plus' // 确保导入ElMessageBox

/** 工程采购计划明细 表单 */
defineOptions({ name: 'PurchaseEngineeringDetailForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<PurchasePlanSaveReqVO>({})
const initialFormData = ref<PurchasePlanSaveReqVO>(JSON.parse(JSON.stringify(formData.value)))
const disabled = computed(() => formType.value === 'detail')
const formRules = reactive({
  purchaseType: [
    {
      required: true,
      message: '采购类型不能为空',
      trigger: 'change'
    }
  ],
  planName: [
    { required: true, message: '采购事项名称不能为空', trigger: 'blur' },
    { max: 50, message: '采购事项名称不能超过50个字符', trigger: 'blur' }
  ],
  projectName: [
    { required: true, message: '项目名称不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.value.planName) {
          callback(new Error('项目名称必须与采购事项名称相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  budgetDepartmentId: [{ required: true, message: '预算归属部门不能为空', trigger: 'change' }],
  applicationDepartmentId: [{ required: true, message: '需求使用部门不能为空', trigger: 'change' }],
  purchaseMethod: [{ required: true, message: '采购方式不能为空', trigger: 'change' }],
  warrantyPeriod: [{ max: 20, message: '质保期/维保期不能超过20个字符', trigger: 'blur' }],
  originalContractAmount: [
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: '原合同金额必须为数字，最多保留两位小数',
      trigger: 'blur'
    }
  ],
  contractPerformance: [
    { max: 400, message: '合同使用履约情况不能超过400个字符', trigger: 'blur' }
  ],
  estimatedPriceSource: [
    { max: 400, message: '本次采购预估单价来源说明不能超过400个字符', trigger: 'blur' }
  ],
  requiredDeliveryTime: [{ required: true, message: '需到货时间不能为空', trigger: 'change' }],
  constructionTime: [{ required: true, message: '施工时间不能为空', trigger: 'change' }],
  construction: [{ required: true, message: '施工日期不能为空', trigger: 'change' }],
  constructionLeader: [
    { required: true, message: '施工期间负责人不能为空', trigger: 'blur' },
    { max: 20, message: '施工期间负责人不能超过20个字符', trigger: 'blur' }
  ],
  implementationTeam: [{ required: true, message: '实施小组组成不能为空', trigger: 'blur' }],
  negotiationMethod: [{ required: true, message: '谈判报价方式不能为空', trigger: 'blur' }],
  supplierSelectionPrinciple: [
    { required: true, message: '供应商选择原则不能为空', trigger: 'blur' }
  ],
  // 动态校验：根据采购类型验证对应的明细数组
  serviceDetailSaveReqVOS: [
    {
      validator: (rule, value: any[], callback: (error?: string) => void) => {
        if (formData.value.purchaseType === 'SERVICE' && (value?.length === 0 || !value)) {
          callback('请添加服务类采购明细')
          message.error('请添加服务类采购明细')
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  equipmentDetailSaveReqVOS: [
    {
      validator: (rule, value: any[], callback: (error?: string) => void) => {
        if (formData.value.purchaseType === 'EQUIPMENT' && (value?.length === 0 || !value)) {
          callback('请添加设备类采购明细')
          message.error('请添加设备类采购明细')
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  engineeringDetailSaveReqVOS: [
    {
      validator: (rule, value: any[], callback: (error?: string) => void) => {
        if (formData.value.purchaseType === 'ENGINEERING' && (value?.length === 0 || !value)) {
          callback('请添加工程类采购明细')
          message.error('请添加工程类采购明细')
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  materialDetailSaveReqVOS: [
    {
      validator: (rule, value: any[], callback: (error?: string) => void) => {
        if (formData.value.purchaseType === 'MATERIAL' && (value?.length === 0 || !value)) {
          message.error('请添加物料类采购明细')
          callback('请添加物料类采购明细')
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  minorDetailSaveReqVOS: [
    {
      validator: (rule, value: any[], callback: (error?: string) => void) => {
        const { purchaseType } = formData.value
        if (
          (purchaseType === 'DIRECT' || purchaseType === 'MINOR') &&
          (value?.length === 0 || !value)
        ) {
          callback('请添加小额类采购明细')
          message.error('请添加小额类采购明细')
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})
const formRef = ref() // 表单 Ref

// -------------------------- 核心修改：部门下拉框回显与搜索优化 --------------------------
const DeptPageList = ref<DeptVO[]>([]) // 部门下拉显示列表
const deptAllList = ref<DeptVO[]>([]) // 完整部门列表（缓存所有部门，解决回显问题）

/** 1. 加载完整部门列表（仅加载一次，避免重复请求） */
const loadAllDepts = async () => {
  if (deptAllList.value.length > 0) return deptAllList.value
  try {
    const data = await getSimpleDeptList()
    deptAllList.value = data || []
    return data
  } catch (error) {
    deptAllList.value = []
    return []
  }
}

/** 2. 确保已选部门在下拉列表中（回显时补全缺失数据） */
const ensureSelectedDeptsInList = async () => {
  await loadAllDepts()
  // 提取已选的部门ID（预算归属部门 + 需求使用部门）
  const selectedDeptIds = [
    formData.value.budgetDepartmentId,
    formData.value.applicationDepartmentId
  ].filter(Boolean)

  // 检查并添加缺失的部门到显示列表
  selectedDeptIds.forEach((id) => {
    const isExist = DeptPageList.value.some((item) => item.id === id)
    if (!isExist) {
      const dept = deptAllList.value.find((item) => item.id === id)
      if (dept) DeptPageList.value.push(dept)
    }
  })
}

/** 3. 部门搜索过滤方法（结合完整列表，确保搜索与回显兼容） */
const handleDeptFilter = async (query?: string) => {
  await loadAllDepts()

  // 提取已选部门（确保回显数据不丢失）
  const selectedDepts = [formData.value.budgetDepartmentId, formData.value.applicationDepartmentId]
    .filter(Boolean)
    .map((id) => deptAllList.value.find((dept) => dept.id === id))
    .filter(Boolean)

  // 按查询条件过滤部门列表
  let filteredDepts: DeptVO[] = []
  if (!query) {
    // 无搜索时：显示完整列表（若数据量过大，可改为 slice(0, 200) 兼顾性能）
    filteredDepts = [...deptAllList.value]
  } else {
    // 有搜索时：按部门名称模糊匹配
    filteredDepts = deptAllList.value.filter((dept) =>
      dept.name.toLowerCase().includes(query.toLowerCase())
    )
  }

  // 合并已选部门与过滤结果，去重后更新显示列表
  DeptPageList.value = Array.from(
    new Map([...selectedDepts, ...filteredDepts].map((dept) => [dept.id, dept])).values()
  )
}

/** 4. 优化部门列表初始化方法（复用完整列表缓存） */
const getDeptPageApi = async () => {
  await loadAllDepts()
  // 初始化显示列表（默认显示所有部门，或按需求限制条数）
  DeptPageList.value = [...deptAllList.value]
  // 确保已选部门在列表中（针对编辑场景）
  await ensureSelectedDeptsInList()
}
// -----------------------------------------------------------------------------------

/** 监听部门切换（原有逻辑保留） */
watch(
  () => formData.value.budgetDepartmentId, // 预算归属部门
  (newValue) => {
    const matchedDept = deptAllList.value.find((item) => item.id === newValue) // 从完整列表查找
    formData.value.budgetDepartmentName = matchedDept?.name || ''
  }
)
watch(
  () => formData.value.applicationDepartmentId, // 需求申请部门
  (newValue) => {
    const matchedDept = deptAllList.value.find((item) => item.id === newValue) // 从完整列表查找
    formData.value.applicationDepartmentName = matchedDept?.name || ''
  }
)

/** 打开弹窗（修改：加载完整部门列表并补全回显） */
const timeRangeConfigs = [
  {
    start: 'originalContractStartTime',
    end: 'originalContractEndTime',
    target: 'originalContractTime'
  },
  { start: 'constructionStartTime', end: 'constructionEndTime', target: 'construction' }
]

// 子列表 数据映射（原有逻辑保留）
const respListMap = {
  // 获取数据时的映射
  SERVICE: 'serviceDetailRespVOS',
  EQUIPMENT: 'equipmentDetailRespVOS',
  ENGINEERING: 'engineeringDetailRespVOS',
  MATERIAL: 'materialDetailRespVOS',
  DIRECT: 'minorDetailRespVOS',
  MINOR: 'minorDetailRespVOS'
}
const typeMap = {
  // 保存数据时的映射
  SERVICE: 'serviceDetailSaveReqVOS',
  EQUIPMENT: 'equipmentDetailSaveReqVOS',
  ENGINEERING: 'engineeringDetailSaveReqVOS',
  MATERIAL: 'materialDetailSaveReqVOS',
  DIRECT: 'minorDetailSaveReqVOS',
  MINOR: 'minorDetailSaveReqVOS'
}
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  resetForm()
  dialogTitle.value = t('action.' + type)
  formType.value = type
  await getDeptPageApi() // 加载部门列表（使用优化后的方法）

  if (id) {
    formLoading.value = true
    try {
      formData.value = await PurchasePlanApi.getPurchasePlan(id)
      // 时间格式转换（原有逻辑保留）
      timeRangeConfigs.forEach(({ start, end, target }) => {
        const hasStart = typeof formData.value[start] === 'number'
        const hasEnd = typeof formData.value[end] === 'number'
        if (hasStart && hasEnd) {
          formData.value[target] = [
            formatDate(formData.value[start], 'YYYY-MM-DD'),
            formatDate(formData.value[end], 'YYYY-MM-DD')
          ]
        } else if (hasStart) {
          formData.value[target] = [formatDate(formData.value[start], 'YYYY-MM-DD'), null]
        } else if (hasEnd) {
          formData.value[target] = [null, formatDate(formData.value[end], 'YYYY-MM-DD')]
        }
      })
      const singleTimeFields = ['constructionTime', 'requiredDeliveryTime']
      singleTimeFields.forEach((field) => {
        if (typeof formData.value[field] === 'number') {
          formData.value[field] = formatDate(formData.value[field], 'YYYY-MM-DD')
        }
      })
      // 采购明细数据映射（原有逻辑保留）
      const currentPurchaseType = formData.value.purchaseType
      const respListKey = respListMap[currentPurchaseType]
      const saveListKey = typeMap[currentPurchaseType]
      if (respListKey && saveListKey) {
        formData.value[saveListKey] = formData.value[respListKey] || []
      } else {
        console.error(`未找到采购类型【${currentPurchaseType}】对应的列表字段映射`)
      }
      // 补全已选部门到下拉列表（关键：编辑时确保部门回显）
      await ensureSelectedDeptsInList()
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 项目名称和采购事项名称同步（原有逻辑保留） */
watch(
  () => formData.value.planName,
  (newValue) => {
    formData.value.projectName = newValue
  }
)

/* 小额 非 小额切换（原有逻辑保留） */
const type = ref<String>('NoSmall')
watch(
  () => formData.value.purchaseType,
  (newValue, oldValue) => {
    type.value = newValue === 'DIRECT' || newValue === 'MINOR' ? 'Small' : 'NoSmall'
    // 切换采购类型时重置表单（排除 purchaseType 字段）
    if (oldValue !== undefined) {
      // 避免初始化时重置
      const resetData = JSON.parse(JSON.stringify(initialFormData.value))
      formData.value = {
        ...resetData,
        purchaseType: newValue // 保留当前选择的类型
      }
    }
  },
  {
    immediate: true // 立即执行一次回调
  }
)
/* 监听施工日期变化计算总时长（原有逻辑保留） */
const dayLength = ref(0)
watch(
  () => formData.value.construction,
  (newValue) => {
    if (newValue && newValue[0] && newValue[1]) {
      const startDate = new Date(newValue[0])
      const endDate = new Date(newValue[1])
      const timeDiff = endDate.getTime() - startDate.getTime()
      dayLength.value = Math.ceil(timeDiff / (1000 * 3600 * 24))
    }
  },
  {
    immediate: true // 立即执行一次回调
  }
)

/** 打开导入表格（原有逻辑保留） */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open(formData.value.purchaseType)
}
/** 导入Excel 模板（原有逻辑保留） */
const importHandler = (data: any) => {
  // 失败处理：显示第一条失败信息
  if (data?.failList?.length > 0) {
    ElMessageBox.alert(data.errorMessageList, '导入失败', {
      confirmButtonText: 'OK'
    })
    return
  }
  const targetProp = typeMap[formData.value.purchaseType]
  const currentPurchaseType = formData.value.purchaseType

  console.log(targetProp)
  console.log(currentPurchaseType)

  if (targetProp) {
    const updatedList = (data.successList || []).map((item) => ({
      ...item,
      purchaseType: currentPurchaseType
    }))
    formData.value[targetProp] = updatedList
  } else {
    console.error(`未知的采购类型: ${formData.value.purchaseType}`)
  }
}

/** 提交表单（原有逻辑保留，优化时间格式处理） */
const processTimeRange = (obj, sourceKey, startKey, endKey) => {
  if (obj[sourceKey]?.length === 2) {
    try {
      const startTime = new Date(obj[sourceKey][0])
      obj[startKey] = startTime.getTime() || null
      const endTime = new Date(obj[sourceKey][1])
      obj[endKey] = endTime.getTime() || null
      delete obj[sourceKey]
    } catch (error) {
      console.error(`时间格式转换失败`, obj[sourceKey])
    }
  }
}
const processSingleTime = (obj, sourceKey, targetKey) => {
  if (obj[sourceKey]) {
    try {
      const time = new Date(obj[sourceKey])
      obj[targetKey] = time.getTime() || null
    } catch (error) {
      console.error(`${sourceKey} 时间格式转换失败`, obj[sourceKey])
    }
  }
}
/** 1. 提取通用保存逻辑：独立为 saveForm 函数，供「确定提交」和「提交审核」复用 */
const saveForm = async (): Promise<void> => {
  // 第一步：表单校验
  await formRef.value.validate()

  // 第二步：处理表单数据（时间格式转换、数字转换等，复用原有逻辑）
  const data = { ...formData.value }

  // 时间范围字段转换为时间戳
  processTimeRange(
    data,
    'originalContractTime',
    'originalContractStartTime',
    'originalContractEndTime'
  )
  processTimeRange(data, 'construction', 'constructionStartTime', 'constructionEndTime')

  // 单个时间字段转换为时间戳
  processSingleTime(data, 'constructionTime', 'constructionTime')
  processSingleTime(data, 'requiredDeliveryTime', 'requiredDeliveryTime')

  // 数字类型字段处理（避免字符串提交）
  ;['hasNonStandardParts', 'hasProvisionalSum', 'originalContractAmount'].forEach((key) => {
    data[key] = Number(data[key]) || 0
  })

  // 第三步：根据表单类型调用对应保存接口
  if (formType.value === 'create') {
    await PurchasePlanApi.createPurchasePlan(data)
    message.success(t('common.createSuccess'))
  } else {
    await PurchasePlanApi.updatePurchasePlan(data)
    message.success(t('common.updateSuccess'))
  }
}

/** 2. 修改「确定提交」按钮逻辑：调用提取的 saveForm 函数 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  formLoading.value = true
  try {
    await saveForm() // 复用保存逻辑
    dialogVisible.value = false
    emit('success') // 通知父组件刷新数据
  } catch (error) {
    message.error('请填写必填数据') // 捕获保存失败异常
  } finally {
    formLoading.value = false
  }
}

/** 3. 修改「提交审核」按钮逻辑：先保存，再执行审核 */
const auditLoaing = ref(false)
const auditForm = async () => {
  auditLoaing.value = true
  try {
    // 关键步骤：先执行保存（确保数据最新），保存成功后再提交审核
    await saveForm()

    // 保存成功后，执行审核接口调用
    await PurchasePlanApi.auditPurchasePlan(formData.value.id!)
    message.success('提交审核成功')

    // 审核成功后关闭弹窗并通知父组件
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    message.error('提交审核失败，请检查数据后重试') // 捕获保存或审核的异常
  } finally {
    auditLoaing.value = false
  }
}

/** 重置表单（原有逻辑保留） */
const resetForm = () => {
  Object.keys(formData.value).forEach((key) => {
    formData.value[key] = undefined
  })
  formRef.value?.resetFields()
}
</script>